package com.hxkj.interceptor;


import com.hxkj.domain.po.AuthUser;
import com.hxkj.service.UserService;
import com.hxkj.token.annotation.LoginAuthor;
import com.hxkj.token.enums.TokenExceptionEnum;
import com.platform.common.domain.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义参数转换器
 * <p>
 * Create by chenwei on 2018/5/29 14:00
 */
@Component
@Slf4j
public class LoginAuthorArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private UserService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(LoginAuthor.class) && parameter.getParameterType().equals(AuthUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        Map<String, String> headersMap = getHeadersInfo(request);
         String accessToken = headersMap.get("accesstoken");
        if (StringUtils.isBlank(accessToken)) {
            throw new CustomException(TokenExceptionEnum.TOKEN_NOT_EXIST);
        }
        AuthUser authUser = userService.getUserInfoByToken(accessToken);
        if (authUser == null) {
            throw new CustomException(TokenExceptionEnum.TOKEN_NOT_EXIST);
        }
        return authUser;
    }

    /**
     * get request headers
     *
     * @param request
     * @return
     */
    private Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }


}
